# —————————————————————————————————————————————————————————————————— #
import torch
import torch.nn as nn
import torch.nn.functional as F
import sys
sys.path.append("./")
import mymodel.utils as utils
torch.manual_seed(1337)

# —————————————————————————————————————————————————————————————————— #
'''超参数'''
device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu")
batch_size = 4
block_size = 8
max_iter = 10000
eval_iter = 200
lr = 1e-3
eval_interval = 500
n_embd = 32

# —————————————————————————————————————————————————————————————————— #
'''读入数据'''
with open("./TRANSFORMER/dataset.txt", "r", encoding="utf-8") as f:
    text = f.read()
text_len = len(text)
chars = sorted(list(set(text))) # 提取所有不重复字符并放在一个列表中排序
vocab_size = len(chars)

# —————————————————————————————————————————————————————————————————— #
'''解码编码器索引字符相互转化'''
stoi = {ch:idx for idx,ch in enumerate(chars)}
itos = chars
encoder = lambda s: [stoi[c] for c in s]
decoder = lambda idxs: "".join([itos[idx] for idx in idxs])

# —————————————————————————————————————————————————————————————————— #
'''把数据分成训练集和验证集'''
data = torch.tensor(encoder(text), dtype=torch.long) # 全文的索引
n_90 = int(text_len*0.9)
train_data = data[:n_90]
val_data = data[n_90:]
# —————————————————————————————————————————————————————————————————— #
'''在评估模式下同时对训练和测试进行损失评估，取几个随机批量的平均值'''
@torch.no_grad
def estimate_loss():
    out = {}
    model.eval()
    for split in ["train", "val"]:
        losses = torch.zeros(eval_iter)
        for k in range(eval_iter):
            X, Y = get_batch(split)
            _, loss = model(X, Y)
            losses[k] = loss.mean()
        out[split] = losses.mean()
    model.train()
    return out

# —————————————————————————————————————————————————————————————————— #
'''获取一批输入输出 y的位置对应x的target'''
def get_batch(mode="train"):
    (data, data_len) = (train_data, n_90) if mode == "train" else (val_data, text_len-n_90)
    idxs = torch.randint(0, data_len-1-block_size, (batch_size,)) # 生成一个起始索引
    x = torch.stack([data[idx:idx+block_size] for idx in idxs]) # 根据索引生成批量数据(batch_size, block_size)
    y = torch.stack([data[idx+1:idx+block_size+1] for idx in idxs]) # x往后偏移一位
    x, y = x.to(device), y.to(device)
    return x, y
# —————————————————————————————————————————————————————————————————— #
class BiGramModule(nn.Module):
    def __init__(self, vocab_size) -> None:
        super().__init__()
        self.vocab_to_prob_table = nn.Embedding(vocab_size, vocab_size)
    
    def forward(self, X, Targets=None):
        # X's shape is (B, T)
        # X's shape is (B, T)
        logits = self.vocab_to_prob_table(X)
        # logits's shape is (B, T, C).C: Channels in CNN is different color channels,
        #  here is different meaning of a token(dims of embedding)
        if Targets is not None:
            B, T, C = logits.shape
            logits = logits.view(B*T, C)
            Targets = Targets.view(B*T)
            loss = torch.nn.functional.cross_entropy(logits, Targets)
            return logits, loss
        return logits
    
    def generater(self, idx, new_tokens_len):
        # 生成时只有一个批次
        # 把所有的idx收集起来是因为后面有根据前面多个预测的模型
        for _ in range(new_tokens_len):
            logits = self.forward(idx)
            logits = logits[:, -1]
            # print(logits.shape)
            # 取最后一个因为是二元模型
            probs = nn.functional.softmax(logits, dim=1)
            idx_next = torch.multinomial(probs, 1, True)
            idx = torch.cat((idx, idx_next), dim=1)
        return idx

# —————————————————————————————————————————————————————————————————— #
@utils.timer
def train():
    print(f"# —————— start training on {device} —————— #")
    for iters in range(max_iter):
        bx, by = get_batch()
        _, loss = model(bx, by)
        optim.zero_grad(set_to_none=True)
        loss.backward()
        optim.step()
        if iters%eval_interval==0:
            losses = estimate_loss()
            print(f"[step {iters}] {losses}")

# —————————————————————————————————————————————————————————————————— #
model = BiGramModule(vocab_size).to(device)
optim = torch.optim.AdamW(model.parameters(), lr=1e-3)
train()
test_x = torch.zeros((1,1), dtype=torch.long, device=device)
losses = estimate_loss()
print(f"[loss]:{losses}")
print(f"[generate test]:{decoder(model.generater(test_x, eval_iter)[0].tolist())}")

# —————————————————————————————————————————————————————————————————— #
